var express = require('express');
var addressRouter = express.Router();
const SQLQuery = require('../utils/query.js');


addressRouter.post('/mini/addAddress', async function (req, res) {
    try {
        let queryObj = req.body;
        var addSql = 'insert into address(uid,name,mobile,area,address,createTime) values(?,?,?,?,?,?)';
        var addSqlParams = [queryObj.uid, queryObj.name, queryObj.mobile, queryObj.area, queryObj.address, new Date()];
        await SQLQuery.query(addSql, addSqlParams)
        res.send(global.common.resJson(0, 'success', null))
    } catch (err) {
        res.send(err)
    }
})

addressRouter.post('/mini/list', async function (req, res) {
    try {
        let queryObj = req.body;
        var sql = `SELECT * FROM address WHERE uid = ${queryObj.uid} AND isDeleted = 0`;
        let result = await SQLQuery.query(sql)
        res.send(global.common.resJson(0, 'success', result))
    } catch (err) {
        res.send(err)
    }
})

addressRouter.post('/mini/del', async function (req, res) {
    try {
        let queryObj = req.body;
        var sql = `update address set isDeleted = 1 where id = ${queryObj.id}`;
        let result = await SQLQuery.query(sql)
        res.send(global.common.resJson(0, 'success', result))
    } catch (err) {
        res.send(err)
    }
})

addressRouter.post('/mini/detail', async function (req, res) {
    try {
        let queryObj = req.body;
        var sql = `select * from address where id = ${queryObj.id}`;
        let result = await SQLQuery.query(sql)
        res.send(global.common.resJson(0, 'success', result[0]))
    } catch (err) {
        res.send(err)
    }
})

addressRouter.post('/mini/setDefault', async function (req, res) {
    try {
        let queryObj = req.body;
        var sql = `update address set isDefault = 0 where uid = ${queryObj.uid}`;
        var sql2 = `update address set isDefault = 1 where id = ${queryObj.id} AND uid = ${queryObj.uid}`;
        let result = await SQLQuery.query(sql);
        let result2 = await SQLQuery.query(sql2);
        res.send(global.common.resJson(0, 'success', null))
    } catch (err) {
        res.send(err)
    }
})

addressRouter.post('/mini/getDefault', async function (req, res) {
    try {
        let queryObj = req.body;
        var sql = `select * from address where uid = ${queryObj.uid} AND isDefault = 1`;
        let result = await SQLQuery.query(sql)
        res.send(global.common.resJson(0, 'success', result[0]))
    } catch (err) {
        res.send(err)
    }
})


module.exports = addressRouter;